package com.sean.listener;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.Properties;
import java.util.Map.Entry;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;

public class EnviromentListener implements ServletContextListener {

    private final Logger logger = Logger.getLogger(EnviromentListener.class);
    private static final String ENV_CONFIGURATION = "envConfiguration";

    public void contextDestroyed(ServletContextEvent sce) {

    }

    @SuppressWarnings("unchecked")
    public void contextInitialized(ServletContextEvent sce) {
	ServletContext context = sce.getServletContext();
	String env = context.getInitParameter(ENV_CONFIGURATION);

	if (null == env || env.equals("")) {
	    return;
	}
	logger.debug("Begin load properties");

	final Properties globalProps = new Properties();

	String[] props = env.split(",");
	for (String prop : props) {
	    try {
		if (logger.isDebugEnabled()) {
		    logger.debug("Load enviroment variable from file " + prop);
		}
		globalProps.load(getClass().getResourceAsStream(prop));
	    } catch (IOException e) {
		logger.error("Load enviroment variables from " + prop
			+ " failed!", e);
	    }
	}

	// Set them all in context variable. Be careful for conflict
	try {
	    for (Entry entry : globalProps.entrySet()) {
		String keyStr = (String) entry.getKey();
		String actualKey = keyStr.replaceAll(".", "_");
		logger.debug(MessageFormat.format(
			"Load variable {0}, you can access it by {1}", keyStr,
			actualKey));
		context.setAttribute(keyStr.replaceAll(".", "_"), entry
			.getValue());
	    }
	} catch (Throwable t) {
	    t.printStackTrace();
	}

	logger.debug("............. Load ...............");

    }

}
